//
//  Data.m
//  ExportTableTool
//
//  Created by apple on 2019/4/15.
//  Copyright © 2019年 apple. All rights reserved.
//

#import "Data.h"
#import <sqlite3.h>

static sqlite3 *db;

@implementation Data

// 打开数据库
+ (void)openSql{
    sqlite3_shutdown();
    sqlite3_config(SQLITE_CONFIG_SERIALIZED);
    
    if (sqlite3_open([[self getDataPath] UTF8String], &db)) {
        NSLog(@"数据库打开失败");
    }
    
    sqlite3_exec(db, "create table if not exists data (\
                 id integer primary key AUTOINCREMENT, \
                 name text, \
                 content text)", NULL, NULL, NULL);
}

+ (void)closeSql{
    sqlite3_close(db);
}

+ (void)saveData:(NSString *)data key:(NSString *)key{
    NSString *sqlExec = [NSString stringWithFormat:@"insert into data values (NULL,'%@','%@')",key,data];
    sqlite3_exec(db, [sqlExec UTF8String], NULL, NULL, NULL);
}

+ (NSString *)getDataForKey:(NSString *)key{
    // 找到符合条件id最大的记录
    NSString *sqlExec = [NSString stringWithFormat:@"SELECT * from data where (id IN (SELECT MAX(id) FROM data where name = '%@'))",key];
    
    NSString *content = @"";
    
    sqlite3_stmt *statement = 0x00;
    
    if (sqlite3_prepare_v2(db, [sqlExec UTF8String], -1, &statement, NULL) == SQLITE_OK) {
        while (sqlite3_step(statement) == SQLITE_ROW){
            char *contentChar = (char*)sqlite3_column_text(statement, 2);
            contentChar = contentChar == NULL?"":contentChar;
            content = [[NSString alloc] initWithUTF8String:contentChar];;
        }
    }
    sqlite3_finalize(statement);
    
    return content;
}

+ (NSString *)getDataPath{
    NSString *pathString = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"db"];
    return pathString;
}

@end
